using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace ClubWebsite
{
    public class Global : System.Web.HttpApplication
    {
        protected static bool _applicationStartedSucessfully = false;

        protected void Application_Start(object sender, EventArgs e)
        {
            // Test log files
            Functions.WriteLogEntry("Log test", false, null);
            Functions.WriteLogEntry("Log test", false, new ApplicationException("Test log file"));

            // Test database connection.
            if (ConfigurationManager.ConnectionStrings["ConnectionString"] == null)
            {
                throw new Exception("Connection string missing in web.config.");
            }
            if (String.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                throw new Exception("Connection string must be set in web.config.");
            }
            if (!Functions.GetDatabaseDataContext().DatabaseExists())
            {
                throw new Exception("The connection string is invalid or the database does not exist.");
            }

            // Note that the application has started okay
            Functions.WriteLogEntry("Application started at " + System.Web.Hosting.HostingEnvironment.SiteName + ".", false, null);

            // Let the application know that it started sucessfully
            _applicationStartedSucessfully = true;
        }

        protected void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown
            Functions.WriteLogEntry("Application ended at " + System.Web.Hosting.HostingEnvironment.SiteName + ".", false, null);
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            // Log the error
            Exception exception = Server.GetLastError().GetBaseException();
            System.Text.StringBuilder logEntry = new System.Text.StringBuilder();

            logEntry.Append("Site:\t");
            try
            {
                logEntry.AppendLine(System.Web.Hosting.HostingEnvironment.SiteName);
            }
            catch (Exception ex)
            {
                logEntry.AppendLine(String.Format("Exception ({0}).", ex.Message));
            }
            
            logEntry.Append("Sender:\t");
            try
            {
                logEntry.AppendLine(sender.ToString());
            }
            catch (Exception ex)
            {
                logEntry.AppendLine(String.Format("Exception ({0}).", ex.Message));
            }

            logEntry.Append("URL:\t");
            try
            {
                logEntry.AppendLine(Request.Url.ToString());
            }
            catch (Exception ex)
            {
                logEntry.AppendLine(String.Format("Exception ({0}).", ex.Message));
            }

            logEntry.Append("Referrer:\t");
            try
            {
                logEntry.AppendLine(Request.UrlReferrer.OriginalString);
            }
            catch (Exception ex)
            {
                logEntry.AppendLine(String.Format("Exception ({0}).", ex.Message));
            }

            logEntry.Append("User Agent:\t");
            try
            {
                logEntry.AppendLine(Request.UserAgent);
            }
            catch (Exception ex)
            {
                logEntry.AppendLine(String.Format("Exception ({0}).", ex.Message));
            }

            Functions.WriteLogEntry(logEntry.ToString(), true, exception);

            // Ignore favicon not found exceptions during debugging
#if (DEBUG)
    if (Request.Url.ToString().EndsWith("favicon.ico"))
    {
        return;
    }
#endif

            // Check if the Response object and current HttpContext are available. If they are, the expection
            // was caused by a user, so redirect them to an error page. Else, log the exception since there is
            // no one to report the problem to.
            if ((HttpContext.Current.Response != null) && (HttpContext.Current != null))
            {
                // Check if the application is in debug mode. If it is, display the normal, technicial, error
                // message. If it is not in debugging mode, redirect the user to an error page.
                if ((!HttpContext.Current.IsDebuggingEnabled) && (!Request.IsLocal))
                {
                    // Redirect the user to a 'site unavailable' page if the application hasn't loaded sucessfully
                    if (!_applicationStartedSucessfully)
                    {
                        HttpContext.Current.Response.Redirect("~/SiteMaintenance.htm");
                    }
                    else if (exception != null)
                    {
                        Session["LastException"] = exception;
                        HttpContext.Current.Response.Redirect("~/Error.aspx?Message=" + HttpUtility.HtmlEncode(exception.Message).Replace("\r\n", "<br />"));
                    }
                    else
                    {
                        HttpContext.Current.Response.Redirect("~/Error.aspx");
                    }
                }
            }
            else
            {
                Functions.WriteLogEntry("Sender:\t" + sender.ToString() + "URL:\tN/A", true, exception);
            }
        }

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.IsDebuggingEnabled)
            {
                Functions.WriteLogEntry("Application_BeginRequest: URL is " + Request.Url.ToString(), false, null);
            }
        }
    }
}